package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * UserService
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2024/2/22 10:25:58
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(String code) {
        // 1. 验票
        HashMap<String, String> params = new HashMap<>();
        params.put("appid", "wx08e29286ecb4b682");
        params.put("secret", "0673d2a99fd22acbe9d9a98d9f0a275e");
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String responseJson = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSON.parseObject(responseJson);
        // 查询刘姥姥是否存在
        String openid = jsonObject.getString("openid");
        User userQuery = new User();
        userQuery.setOpenid(openid);
        User user = userMapper.selectOne(userQuery);
        if (Objects.isNull(user)) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        // 返回token -- 为了后续访问资源 知道是谁
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
        return userLoginVO;
    }
}
